/*
daytime tcp server.
**/

#include <error.h>
#include <wrapfunc.h>
#include <sockfunc.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>


int
main(int argc, char **argv) {
	if (argc < 2) 
		error_quit("usage: %s port", argv[0]);
	int port = atoi(argv[1]);

	struct sockaddr_in local_addr;
	memset(&local_addr, 0, sizeof(local_addr));
	local_addr.sin_family = AF_INET;
	local_addr.sin_port = htons(port);
	local_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int listen_fd = Socket(AF_INET, SOCK_STREAM, 0);
	Bind(listen_fd, (struct sockaddr*)&local_addr, sizeof(local_addr));
	Listen(listen_fd, 1024);
	error_msg("wait for clients");

	char buf[1024];
	int connfd;
	time_t tick;
    struct sockaddr_in connaddr;
    socklen_t len;
	for (;;) {
		len = sizeof(connaddr);
		connfd = Accept(listen_fd, (struct sockaddr*)&connaddr, &len);
		error_msg("new connection fd:%d addr:%s", connfd, sock_ntop((struct sockaddr*)&connaddr, len));

		tick = time(NULL);
		snprintf(buf, sizeof(buf), "%.24s\r\n", ctime(&tick));
		Write(connfd, buf, strlen(buf));
		Close(connfd);
	}
	return 0;
}
